package cn.may.easyexcel;

import cn.may.entity.Student;
import cn.may.mybatisplus.repository.StudentDao;
import cn.may.mybatisplus.service.StudentService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author May
 * @date 2020/10/29 13:40
 * @desc
 */
@Slf4j
public class UserDataListener extends AnalysisEventListener<Student> {
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    private StudentService studentService;
    List<Student> list = new ArrayList<>();

    /**
     * 每次创建Listener的时候需要把spring管理的类传进来
     * @param studentService dao or service
     */
    public UserDataListener(StudentService studentService) {
        this.studentService = studentService;
    }

    @Override
    public void invoke(Student student, AnalysisContext context) {
//        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(student);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            // 写入数据库
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要写入数据库，确保最后遗留的数据也存储到数据库
        saveData();
//        log.info("所有数据解析完成！");
    }

    /**
     * 写入数据库
     */
    public void saveData() {
//        log.info("{}条数据，开始存储数据库！", list.size());
        studentService.saveBatch(list);
//        for (Student student: list) {
//            studentService.save(student);
//
//        }
//        System.out.println("userData: " + list);
//        log.info("存储数据库成功！");
    }
}
